package com.fatgirl.load.loadStrategy
{
	import com.fatgirl.load.LoadData;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;

	/**
	 *  
	 * swf\png\gif图片 加载器
	 * @author iceman
	 * 
	 */
	public class LoaderStrategy extends LoadStrategy implements ILoadStrategy
	{
		private var m_loader:Loader;
		private var m_url:String;
		public function LoaderStrategy()
		{
		}
		public override function load(_url:String):void
		{
			m_url = _url;
			m_loader = new Loader;
			var t_request:URLRequest = new URLRequest(_url);
			var t_context:LoaderContext = new LoaderContext();
			t_context.applicationDomain = ApplicationDomain.currentDomain;
			//t_context.allowLoadBytesCodeExecution = true;
			addAllListener();
			m_loader.load(t_request,t_context);
		}
		/**
		 * 停止并移除加载 
		 * 
		 */
		public override final function unLoad():void
		{
			removeAllListener();
			m_loader.unloadAndStop(true);
			m_loader.unload();
			m_loader = null;
			//ftrace(this,m_url+"LoaderStrategy：unLoad");
		}
		
		/**
		 * 直接从二进制中加载
		 *  
		 * @param _byte 已经加载的内容
		 * @param _url  原始加载的URL 保留url用来传递给控制器便于控制
		 * 
		 */
		public function loadBytes(_byte:ByteArray,_url:String):void
		{
			m_url = _url;
			m_loader = new Loader;
			var t_context:LoaderContext = new LoaderContext();
			t_context.applicationDomain = ApplicationDomain.currentDomain;
			//设置此属性为了适应AIR的沙箱问题
			//t_context.allowLoadBytesCodeExecution = true;
			addAllListener();
			m_loader.loadBytes(_byte,t_context);
		}
		private function completeHandler(e:Event):void
		{
			this.complete(m_loader.content);
			unLoad();
		}
		private function progressHandler(e:ProgressEvent):void
		{
			var t_percent:int = ((e.bytesLoaded/e.bytesTotal)*100)>>0;
			this.progress(t_percent);
		}
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			this.ioError(m_url);
			unLoad();
		}
		private function openHandler(e:Event):void
		{
			this.open(m_url);
		}
		private function addAllListener():void
		{
			m_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
			m_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			m_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			m_loader.contentLoaderInfo.addEventListener(Event.OPEN,openHandler);
		}
		private function removeAllListener():void
		{
			m_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,completeHandler);
			m_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
			m_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			m_loader.contentLoaderInfo.removeEventListener(Event.OPEN,openHandler);
		}
	}
}